package main

import (
	"flag"
	"os"
	"path/filepath"

	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"originforce.club/bilin-mock/conf"
	"originforce.club/bilin-mock/internal/rest"
)

var (
	pgConfPtr   *conf.PgSection
	webConfPtr  *conf.WebSection
	varsConfPtr *conf.VarsSection
	// flagC         string
	slog *zap.SugaredLogger
)

func main() {
	initLog()
	readConfig()

	slog.Debugf("pgConf => %+v", *pgConfPtr)
	slog.Debugf("webConf => %+v", *webConfPtr)
	slog.Debugf("varsConf => %+v", *varsConfPtr)

	s := rest.NewRestServer(slog, pgConfPtr, webConfPtr, varsConfPtr)
	s.Run()
}

func initLog() {
	c := zap.NewProductionEncoderConfig()
	c.EncodeTime = zapcore.ISO8601TimeEncoder
	c.TimeKey = "time"
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(c),
		zapcore.AddSync(os.Stdout),
		zap.NewAtomicLevelAt(zap.InfoLevel))
	logger := zap.New(core, zap.AddStacktrace(zapcore.FatalLevel), zap.AddCaller())
	defer logger.Sync()
	zap.ReplaceGlobals(logger)
	// logger.Info("initlog", zap.String("name", "hhhhhh"))
	slog = zap.S()
	slog.Infof("global SugaredLogger after %s", "bgs")
}

func readConfig() {
	flag.String("c", "conf/config.toml", "set configuration `file`")
	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
	//解析flag
	pflag.Parse()
	//viper绑定pflag
	viper.BindPFlags(pflag.CommandLine)
	viper.SetConfigType("toml")
	configValue := viper.GetString("c")
	viper.AddConfigPath(filepath.Dir(configValue))
	viper.SetConfigName(filepath.Base(configValue))

	err := viper.ReadInConfig()
	if err != nil {
		slog.Panicf("Fatal error config file: %s \n", err)
	}

	pgConfPtr = conf.ReadPg(viper.Sub("pg"), slog)
	webConfPtr = conf.ReadWeb(viper.Sub("web"), slog)
	varsConfPtr = conf.ReadVars(viper.Sub("vars"), slog)
}
